package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.upload.controller.UploadController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: taft
 * @Date: 2018-10-12 11:06
 */
@Service
public class UploadService {

    @Autowired
    private FastFileStorageClient storageClient;


    private static final Logger logger = LoggerFactory.getLogger(UploadService.class);

    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg");

    public String upload(MultipartFile file) {

        try {
            String contentType = file.getContentType();
            //确认文件的类型
            if (!suffixes.contains(contentType)){
                logger.error("不支持的文件类型：{}",contentType);
                return null;
            }

            //确认文件的内容,ImageIO只能提取图片的内容
            BufferedImage read = ImageIO.read(file.getInputStream());

            if (null==read){
                logger.error("不支持的文件内容");
                return null;
            }

            //校验通过了，要保存文件了

            // 2、保存图片
//            // 2.1、生成保存目录
//            File dir = new File("D:/test/upload");
//            if (!dir.exists()) {
//                dir.mkdirs();
//            }
//            // 2.2、保存图片 cl.jpg
//            file.transferTo(new File(dir, file.getOriginalFilename()));
//
//            // 2.3、拼接图片地址
//            String url = "http://image.leyou.com/upload/" + file.getOriginalFilename();

            // 2.1、获取文件后缀名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");

            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);

            return "http://image.leyou.com/"+storePath.getFullPath();


        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
